package com.yiyun.blog.controller;

import com.yiyun.blog.utils.QiniuUtils;
import com.yiyun.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author Bao
 * @create 2022-05-10-16:13
 */
@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private QiniuUtils qiniuUtils;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file) {
        /**
         * MultipartFile spring中用于接收文件的类型
         * substringAfterLast：截取内容
         * */
        // 原始文件名称：比如 aa.png
        String originalFilename = file.getOriginalFilename();
        // 新创建的唯一名称，防止名称重复
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename,".");
        // 上传文件 上传到七牛云服务器（把图片发放到离用户最近的服务器上）
        boolean upload = qiniuUtils.upload(file, fileName);
        if(upload){
            return Result.success(QiniuUtils.url+fileName);
        }
        return Result.fail(20001,"上传失败");
    }
}
